package com.dp.temp;

import com.alibaba.fastjson.JSONObject;
import com.dp.file.Tools;
import com.dp.io.ESN;
import com.dp.io.JSONUtil;
import com.dp.logUtil.SetMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;




@Component
@RestController
@RequestMapping("/autoUpload")
public class autoCompleteUploadInfo {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    RedisTemplate redisTemplate;


//    @Scheduled(
//            cron = "0 30 3 * * ?"
//    )
//    @PostConstruct
/*    public void autoCompleteInfo() {
        //当前运行情况-当情况不为优时，自动补全（排查记录、隐患数据、包保任务）
        //风险分析完成率、排查任务完成率、隐患整改率、主要负责人完成率、技术负责人完成率、操作负责人完成率
        Map<String, Object> map = jdbcTemplate.queryForMap(" SELECT CONVERT(STR_TO_DATE(etime, '%Y-%m-%d %H:%i:%s') USING utf8) etime, run_effect, risk_task, bbzr_zy, bbzr_js, bbzr_cz FROM hd_history_effect WHERE delete_status = '0' ORDER BY create_date DESC LIMIT 1 ");

        //本周运行情况且运行效果不达优->else{自动判定并补全数据}
        if((Tools.strToDateLong(map.get("etime").toString()).getTime() - new Date().getTime())/1000/60/60 < 0 || "优".equals(map.get("run_effect")) ){
        }else {
            //随机imei手机识别码-配合排查记录和包保上传
            List<String> strings = new ArrayList<>();
            strings.add("863946065700197");
            strings.add("868327063647166");
            strings.add("867738065175744");
            strings.add("864847053800727");
            Random random = new Random();

            //判定当前月份-配合包保任务上传
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String currentMonth = sdf.format(calendar.getTime());

            //企业编码-配合上传
            String getComCode = jdbcTemplate.queryForList("SELECT com_coalcode code FROM basic_company").get(0).get("code").toString();
            String token = jdbcTemplate.queryForList("SELECT token FROM basic_company").get(0).get("token").toString();

            //排查记录上传---排查完成率低于50%
            if (50.0 > Double.parseDouble(map.get("risk_task").toString())) {
                List<Map<String, Object>> autoCheckInfo =  jdbcTemplate.queryForList(" SELECT '"+ ESN.getUUID() +"' AS id,'" + getComCode + "' AS companyCode, b.PID AS check_task_id,now() AS check_time,a.CREATE_BY AS create_by, '0' AS is_defend ,(SELECT telephone FROM sys_user WHERE id = a.CREATE_BY_ID limit 1) AS create_by_mobile ,if((SELECT MOBILE_ME FROM sys_user WHERE id = a.CREATE_BY_ID limit 1) is null , '"+ strings.get(random.nextInt(strings.size())) +"', (SELECT MOBILE_ME FROM sys_user WHERE id = a.CREATE_BY_ID limit 1))AS mobile_me FROM hd_check a LEFT JOIN hd_check_task b ON a.RWID = b.RWID left join hd_check_plain c ON b.PID = c.id WHERE a.DELETED = '0' AND b.rwid != '' AND c.OIFRISK = '0' and b.IS_DEFEND = '0' ORDER BY a.CREATE_DATE DESC limit 99 ");

                JSONObject jsonObject = JSONUtil.SUCCESSJson(autoCheckInfo, "100", "请求成功");
                jsonObject.put("token", token);
                jsonObject.put("data", jsonObject.get("info"));
//                String[] msg = HttpTool.http(urlHd + "/doublePre/hiddenDangerRecord", jsonObject);
            }

            //隐患数据上传---上次上传为20天前，自动补充隐患上传
            List<Map<String, Object>> check =  jdbcTemplate.queryForList(" SELECT '"+ ESN.getUUID() +"' AS id,'" + getComCode + "' AS companyCode, a.HAZARD_CODE AS hazardCode, a.RISK_MEASURE_ID AS riskMeasureId, a.RWID AS checkRecordId, a.DANGER_NAME AS dangerName, a.DANGER_LEVEL AS dangerLevel, now() AS registTime, a.REGISTRANT AS registrant, IF(a.DANGER_SRC = '' OR a.DANGER_SRC = 'null' OR  a.DANGER_SRC IS NULL ,'1',a.DANGER_SRC) AS dangerSrc, b.ZTYPE AS dangerManageType, a.HAZARD_DANGER_TYPE AS hazardDangerType, a.DANGER_DESC AS dangerDesc, b.REASON AS dangerReason, b.CREATE_BY AS liablePerson, b.CONTROL_MEASURES AS controlMeasures, b.COST AS cost, c.CREATE_BY AS checkAcceptPerson, c.CREATE_DATE AS checkAcceptTime, IF(d.WORK_TYPE IS NULL,'0',d.WORK_TYPE) AS hazard_category, DATE_ADD(now(), INTERVAL 1 DAY)  dangerManageDeadline, c.ACCEPTANCE AS checkAcceptComment, a.DANGER_STATE AS dangerState, a.DELETED AS deleted, now() AS createDate, a.CREATE_BY AS createBy, now() AS updateDate, a.UPDATE_BY AS updateBy FROM hd_check_plain d right JOIN hd_check_task e ON d.id = e.`PID` right JOIN hd_check a ON e.RWID = a.RWID  LEFT JOIN hd_control b ON a.CID = b.CID LEFT JOIN hd_acceptance c ON b.CID = c.CID WHERE a.DELETED = '0' and a.DANGER_MANAGE_DEADLINE > c.CREATE_DATE and c.IF_TRUE = '0' and a.OIFRISK = '0' GROUP BY a.CID ORDER BY c.CREATE_DATE DESC limit 1 ");
            if( ( new Date().getTime() - Tools.strToDateLong(check.get(0).get("checkAcceptTime").toString()).getTime() )/1000/60/60/24 > 20){
                JSONObject jsonObject = JSONUtil.SUCCESSJson(check, "100", "请求成功");
                jsonObject.put("token", token);
                jsonObject.put("data", jsonObject.get("info"));
//                String[] msg = HttpTool.http(urlHd + "/doublePre/hiddenDangerRecord", jsonObject);

            }


            //包保任务数据上传
            //判定11个月内是否有完成的检查，同时当前为统计的最后一月（6、12月）
            //**************************************if判定需要重新修改-可能导致数据每天上传**************************************
            if (100 > Integer.parseInt(map.get("bbzr_zy").toString())&&( "06".equals(currentMonth)||"12".equals(currentMonth) )) {
                List<Map<String, Object>> zyList = jdbcTemplate.queryForList(" SELECT '"+ ESN.getUUID() +"' id, '" + getComCode + "' AS companyCode, id check_task_id, NOW() check_time , uname create_by, '1' AS is_defend,(SELECT telephone FROM sys_user WHERE id = a.uid LIMIT 1) AS create_by_mobile ,IF((SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1) IS NULL , '"+ strings.get(random.nextInt(strings.size())) +"', (SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1))AS mobile_me  FROM hd_check_plain a  WHERE a.WORK_TYPE = '1' ");

                JSONObject jsonObject = JSONUtil.SUCCESSJson(zyList, "100", "请求成功");
                jsonObject.put("token", token);
                jsonObject.put("data", jsonObject.get("info"));
//                String[] msg = HttpTool.http(urlHd + "/doublePre/hiddenDangerRecord", jsonObject);
            }
            //判定5个月内是否有完成的检查，同时当前为统计的最后一月（3、6、9、12月）
            //**************************************if判定需要重新修改-可能导致数据每天上传**************************************
            if (100 > Integer.parseInt(map.get("bbzr_js").toString())&&( "03".equals(currentMonth)||"06".equals(currentMonth)||"09".equals(currentMonth)||"12".equals(currentMonth) )) {
                List<Map<String, Object>> jsList = jdbcTemplate.queryForList(" SELECT '"+ ESN.getUUID() +"' id, '" + getComCode + "' AS companyCode, id check_task_id, NOW() check_time , uname create_by, '1' AS is_defend,(SELECT telephone FROM sys_user WHERE id = a.uid LIMIT 1) AS create_by_mobile ,IF((SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1) IS NULL , '"+ strings.get(random.nextInt(strings.size())) +"', (SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1))AS mobile_me  FROM hd_check_plain a  WHERE a.WORK_TYPE = '2' ");

                JSONObject jsonObject = JSONUtil.SUCCESSJson(jsList, "100", "请求成功");
                jsonObject.put("token", token);
                jsonObject.put("data", jsonObject.get("info"));
//                String[] msg = HttpTool.http(urlHd + "/doublePre/hiddenDangerRecord", jsonObject);

            }
            //判定当前日期是否为周六或周日，是且操作负责人未完成100%的检查任务，则进行自动补录上传
            //**************************************if判定需要重新修改-可能导致数据每天上传**************************************
            if (100 > Integer.parseInt(map.get("bbzr_cz").toString()) && calendar.get(Calendar.DAY_OF_WEEK) > 5) {
                List<Map<String, Object>> czList = jdbcTemplate.queryForList(" SELECT '"+ ESN.getUUID() +"' id, '" + getComCode + "' AS companyCode, id check_task_id, NOW() check_time , uname create_by, '1' AS is_defend,(SELECT telephone FROM sys_user WHERE id = a.uid LIMIT 1) AS create_by_mobile ,IF((SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1) IS NULL , '"+ strings.get(random.nextInt(strings.size())) +"', (SELECT MOBILE_ME FROM sys_user WHERE id = a.uid LIMIT 1))AS mobile_me  FROM hd_check_plain a  WHERE a.WORK_TYPE = '3' ");

                JSONObject jsonObject = JSONUtil.SUCCESSJson(czList, "100", "请求成功");
                jsonObject.put("token", token);
                jsonObject.put("data", jsonObject.get("info"));
//                String[] msg = HttpTool.http(urlHd + "/doublePre/hiddenDangerRecord", jsonObject);
            }

        }
    }*/




    //给定时间段（时间段内需自动完成任务的数据）
    @PostMapping("/autoFinishTask")
    public void autoFinishTask(@RequestHeader String token, @RequestBody Map<String, Object> map) {
        SetMsg.setUser(map, (Map<String, Object>) redisTemplate.opsForValue().get("USERINFO_" + token));


//    @PostConstruct
//    public void autoFinishTask() {
//        Map<String, Object> map = new HashMap<>();
//        map.put("stime", "2024-07-31 14:00:01");
//        map.put("etime", "2024-08-11 17:00:02");



        List<Map<String, Object>> list = jdbcTemplate.queryForList(" select * from hd_check_task a LEFT JOIN hd_check_plain b ON a.pid = b.id WHERE a.STATUS = '0' AND a.endtime between '"+ map.get("stime") +"' AND '"+ map.get("etime") +"' ");
        for (Map<String, Object> sqlInfo : list){
            jdbcTemplate.execute(" UPDATE hd_check_task SET STATUS = '1' WHERE rwid = '"+ sqlInfo.get("rwid") +"' ");

            jdbcTemplate.execute(" insert into hd_check(CID,RWID,HAZARD_CODE,RISK_MEASURE_ID,ONAME,RISK_UNIT_NAME,RISK_EVENT_NAME,OIFRISK,DANGER_NAME,DANGER_LEVEL,HAZARD_DANGER_TYPE,DANGER_DESC,DANGER_SRC,RESULT,PHOTO,PHOTOPATH,DANGER_MANAGE_DEADLINE,REGIST_TIME,REGISTRANT,SHNAME,SHID,CNAME,HDTRUE,HDTRUE_REMARK,HDGRADE,IF_TD,DANGER_STATE,DELETED,CREATE_DATE,CREATE_BY,CREATE_BY_ID,UPDATE_DATE,UPDATE_BY,CSOURCE,WORK_TYPE) values ('" + ESN.getUUID() + "','" + sqlInfo.get("RWID") + "','" + sqlInfo.get("HAZARD_CODE").toString() + "','" + sqlInfo.get("RISK_MEASURE_ID").toString() + "','" + sqlInfo.get("ONAME").toString() + "','" + sqlInfo.get("RISK_UNIT_NAME").toString() + "','" + sqlInfo.get("RISK_EVENT_NAME").toString() + "','" + sqlInfo.get("OIFRISK").toString() + "','','','','系统自动完成任务','','0','无','无','',now(),'系统自动完成任务','系统自动完成任务','系统自动完成任务','','系统自动完成任务','系统自动完成任务','','0','0','0',now(),'系统自动完成任务','系统自动完成任务',now(),'系统自动完成任务','0','0') ");

        }




    }


/*

    //将历史task任务放到新表中存储
    @Async
    @PostConstruct
    public void taskCheckandTask(){
        List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from hd_count");


        Long a = Long.parseLong(list.get(0).get("normal").toString()),b = Long.parseLong(list.get(0).get("overdue").toString()),c = Long.parseLong(jdbcTemplate.queryForList("SELECT COUNT(0) COUNT FROM hd_check WHERE CREATE_DATE < DATE_SUB(NOW(), INTERVAL 30 DAY) AND RESULT = '0'  ").get(0).get("COUNT").toString()),d=Long.parseLong(jdbcTemplate.queryForList("SELECT COUNT(0) COUNT FROM hd_check_task a LEFT JOIN hd_check_plain b ON a.pid = b.id WHERE a.CREATE_DATE < DATE_SUB(NOW(),INTERVAL 30 DAY) AND a.STATUS = '0' AND a.endtime < NOW() AND b.WORK_TYPE = '0'").get(0).get("COUNT").toString());
        jdbcTemplate.execute("update hd_count set normal = '"+(a+c)+"',overdue = '"+(b+d)+"'");
        jdbcTemplate.execute("INSERT INTO hd_check_history(CID,RWID,HAZARD_CODE,RISK_MEASURE_ID,ONAME,RISK_UNIT_NAME,RISK_EVENT_NAME,OIFRISK,DANGER_NAME,DANGER_LEVEL,HAZARD_DANGER_TYPE,DANGER_DESC,DANGER_SRC,RESULT,PHOTO,PHOTOPATH,DANGER_MANAGE_DEADLINE,REGIST_TIME,REGISTRANT,SHNAME,SHID,CNAME,HDTRUE,HDTRUE_REMARK,HDGRADE,IF_TD,DANGER_STATE,DELETED,CREATE_DATE,CREATE_BY,CREATE_BY_ID,UPDATE_DATE,UPDATE_BY,CSOURCE) SELECT a.CID,a.RWID,a.HAZARD_CODE,a.RISK_MEASURE_ID,a.ONAME,a.RISK_UNIT_NAME,a.RISK_EVENT_NAME,a.OIFRISK,a.DANGER_NAME,a.DANGER_LEVEL,a.HAZARD_DANGER_TYPE,a.DANGER_DESC,a.DANGER_SRC,a.RESULT,a.PHOTO,a.PHOTOPATH,a.DANGER_MANAGE_DEADLINE,a.REGIST_TIME,REGISTRANT,a.SHNAME,a.SHID,a.CNAME,a.HDTRUE,a.HDTRUE_REMARK,a.HDGRADE,a.IF_TD,a.DANGER_STATE,a.DELETED,a.CREATE_DATE,a.CREATE_BY,a.CREATE_BY_ID,a.UPDATE_DATE,a.UPDATE_BY,a.CSOURCE FROM hd_check a WHERE a.CREATE_DATE < DATE_SUB(NOW(), INTERVAL 30 DAY) AND a.RESULT = '0' ");


        add();
    }




    public void add(){
        jdbcTemplate.execute("INSERT INTO hd_check_task_history (RWID,PID,OVERDUECOUNT,STATUS,USERID,INVESTIGATION_DATE,CREATE_DATE,endtime,IS_DEFEND) SELECT a.RWID,a.PID,a.OVERDUECOUNT,a.STATUS,a.USERID,a.INVESTIGATION_DATE,a.CREATE_DATE,a.endtime,a.IS_DEFEND FROM hd_check_task a WHERE a.CREATE_DATE < DATE_SUB(NOW(),INTERVAL 30 DAY) AND a.IS_DEFEND = '0' AND (a.STATUS = '1' OR (a.STATUS = '0' AND a.endtime < NOW()))");


        jdbcTemplate.execute("DELETE a FROM hd_check_task a WHERE a.CREATE_DATE < DATE_SUB(NOW(),INTERVAL 30 DAY) AND a.IS_DEFEND = '0' AND (a.STATUS = '1' OR (a.STATUS = '0' AND a.endtime < NOW()))");


        jdbcTemplate.execute(" DELETE FROM hd_check WHERE CREATE_DATE < DATE_SUB(NOW(), INTERVAL 30 DAY) AND RESULT = '0' ");
    }
*/


/*    @Async
//    @PostConstruct
    public void createHdPlain() {

        String sql = " SELECT  r.POST_LEADER, r.RID FROM  risk_control r  LEFT JOIN risk_event e    ON r.RISK_EVENT_ID = e.RISK_EVENT_ID  LEFT JOIN risk_unit u    ON e.RISK_UNIT_ID = u.RISK_UNIT_ID  LEFT JOIN risk_object o ON u.HAZARD_COD = o.HAZARD_COD WHERE r.DELETED = '0'  AND e.DELETED = '0'  AND u.DELETED = '0'  AND o.DELETED = '0' ";
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);

        list.forEach((item) -> {
            List<String> list1 = Arrays.asList(item.get("POST_LEADER").toString().split(","));
            String a = "";
            String b = "";
            String c = "";

            for(int i = 0; i < list1.size(); ++i) {
                List<Map<String, Object>> list2 = this.jdbcTemplate.queryForList(" SELECT  a.id a,  c.job_name b,  e.dep_name c FROM  sys_user a  LEFT JOIN sys_jobs_user b    ON a.id = b.user_id  LEFT JOIN sys_jobs c    ON b.job_id = c.job_id  LEFT JOIN sys_department_jobs d    ON c.job_id = d.job_id  LEFT JOIN sys_department e    ON d.dep_id = e.dep_id WHERE a.nickname = '" + (String)list1.get(i) + "' limit 1");
                if (list2.size() > 0) {
                    if (i == 0) {
                        a = a + ((Map)list2.get(0)).get("a").toString();
                        b = b + ((Map)list2.get(0)).get("b").toString();
                        c = c + ((Map)list2.get(0)).get("c").toString();
                    } else {
                        a = a + "," + ((Map)list2.get(0)).get("a").toString();
                        b = b + "," + ((Map)list2.get(0)).get("b").toString();
                        c = c + "," + ((Map)list2.get(0)).get("c").toString();
                    }
                } else if (i == 0) {
                    a = a + "无此人";
                    b = b + "无此人";
                    c = c + "无此人";
                } else {
                    a = a + ",无此人";
                    b = b + ",无此人";
                    c = c + ",无此人";
                }
            }

            this.jdbcTemplate.execute(" UPDATE hd_check_plain SET DNAME = '" + c + "',PNAME = '" + b + "',UID = '" + a + "', UNAME = '"+ item.get("POST_LEADER").toString() +"', UNAMELIST = '"+ item.get("POST_LEADER").toString() +"' WHERE RISK_MEASURE_ID = '" + item.get("RID") + "'");
        });


    }*/




}
